import { useEffect, useState } from "react"

export const isFalsy = (value: unknown) => value === 0 ? false : !value

//在一个函数中，改变传入的对象本身是不好的
export const cleanObject = (object: object) => {
  const result:any = { ...object }
  Object.keys(result).forEach(key => {
    const value = result[key]
    if (isFalsy(value)) {
      delete result[key]
    }
  })
  return result
}

export const useMount = (callback: ()=>void) => {
  useEffect(() => {
    callback()
  }, [])// 使用[]时，使useEffect只在初次加载时执行，避免使用useEffect时，通篇的[],
}

// debounce
export const useDebounce = <V>(value:V, delay?:number) => {
  const [debounceValue, setDebounceValue] = useState(value)
  useEffect(() => {
    // 每次在value变化之后，设置一个定时器
    let timeout = setTimeout(() => setDebounceValue(value), delay)
    // 每次在上一个useEffect处理完成以后在运行
    return () => {
      clearTimeout(timeout)
      console.log('call')
    }
  }, [value, delay])
  return debounceValue
}
